package com.sservice.web.controller.admin;

import com.sservice.common.Constants;
import com.sservice.common.OrderConstants;
import com.sservice.common.PrintContract;
import com.sservice.common.SameUrlData;
import com.sservice.model.dao.IAddressDao;
import com.sservice.model.dao.OrderPaperMapper;
import com.sservice.model.vo.ContractVO;
import com.sservice.model.vo.OrderVo;
import com.sservice.urp.entity.Role;
import com.sservice.urp.entity.User;
import com.sservice.urp.vo.UserVo;
import com.sservice.service.service.*;
import com.sservice.base.entity.dto.BaseResult;
import com.sservice.base.entity.dto.ListResult;
import com.sservice.base.entity.dto.Pagination;
import com.sservice.model.entity.*;
import com.sservice.web.log.Action;
import com.sservice.web.utils.PdfHelper;
import com.sservice.web.utils.PdfUtils;
import com.lowagie.text.DocumentException;
import com.sservice.web.common.Utils;
import freemarker.template.TemplateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/admin/order")
public class OrderController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IOrderService depService;
    @Autowired
    private IAddressDao addressDao;
    @Autowired
    private ExportService exportService;
    @Autowired
    private IClienteleService clienteleService;
    @Autowired
    private IOfferService offerService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IStoreService storeService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private ISaleCommissionService saleCommissionService;
    @Autowired
    private IOrderPaperService orderPaperService;
    @Autowired
    private OrderPaperMapper orderPaperMapper;
    @Autowired
    private IOrderOperateLogService orderOperateLogService;
    @Autowired
    private ISysLogService sysLogService;


    /**
     * 创建
     *
     * @return
     */
    @SameUrlData
    @ResponseBody
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public BaseResult<Integer> create(Order arg) {
        int service_res = depService.insertSelective(arg);
        BaseResult<Integer> res = new BaseResult<Integer>(true, service_res);
        return res;
    }


    /***
     * 申请退款
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryApplyPay", method = RequestMethod.GET)
    public ListResult queryApplyPay(OrderVo arg) {
        arg.setApplyBack("1");
        List orders = depService.queryByPage(arg);
        int total = depService.queryCount(arg);
        Pagination page = new Pagination(arg.getPage(), total, arg.getSize());
        ListResult res = new ListResult(true, orders);
        res.setPage(page);
        return res;
    }


    @ResponseBody
    @RequestMapping(value = "/get", method = RequestMethod.GET)
    public BaseResult<Order> get(Order arg) {
        Order service_res = depService.selectByPrimaryKey(arg.getId());
        return new BaseResult<Order>(true, service_res);
    }

    /***
     *  核销
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/verified/{id}", method = RequestMethod.GET)
    public BaseResult verified(Order arg, HttpServletRequest requset) {
        Order order = depService.selectByPrimaryKey(arg.getId());
        if ("1".equals(order.getVerified())) {
            return new BaseResult(false, "订单已核销!", 403);
        }
        Order order1 = new Order();
        order1.setId(arg.getId());
        order1.setVerified("1");
        order1.setVerifiedTime(new Date());// 核销时间
        int service_res = depService.updateByPrimaryKeySelective(order1);
        if (service_res > 0) {
            sysLogService.log("订单核销", requset, arg.getId(), Action.orderType);
            return new BaseResult(true, "订单核销成功!", 200);
        }
        return new BaseResult(true, "订单核销失败!", 403);

    }

    /**
     * @param arg
     * @return
     */
    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public BaseResult<Object> delete(Order arg) {
//      int service_res = depService.deleteByPrimaryKey(arg.getId());
        return new BaseResult();
//        BaseResult<Object> res = new BaseResult(false, "", 403);
    }

    /**
     * 合同打印
     *
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/print", method = RequestMethod.GET)
    public BaseResult<Object> print(Order arg, HttpServletRequest request) {
        ContractVO cv = new ContractVO();
        Order order = depService.selectByPrimaryKey(arg.getId());
        Offer offer = offerService.selectByPrimaryKey(Integer.valueOf(order.getOfferId()));
        Goods goods = goodsService.selectByPrimaryKey(Integer.valueOf(order.getGoodsId()));
        Clientele clientele = clienteleService.selectByPrimaryKey(Integer.valueOf(order.getClienteleId()));
        cv.setBuyer(order.getClienteleName());
        User u = new User();
        u.setId(Integer.valueOf(offer.getCreatorId()));
        User user = userService.selectDepByPrimaryKey(u);
        if (user != null) {
            cv.setTel(user.getComName());
            cv.setFax(user.getDepName());
            cv.setName(user.getName());
        } else {
            cv.setTel("021-60482075/60482076");
            cv.setFax("021-54738871/54738880");
            cv.setName("王文庆");
        }
        cv.setQualityRequire(offer.getQualityRequire());
        cv.setPaymentCondition(order.getPayCondition() != null ? order.getPayCondition() : " ");
        cv.setCompany(order.getClienteleName());
        cv.setGoodName(order.getGoodsName());
        cv.setQuality(offer.getQualitySpec());
        cv.setContactAddress(clientele.getAddress());
        cv.setContactTel(order.getClienteleUserPhone());
        cv.setContractNO(order.getNo());
        cv.setContactFax(clientele.getFax());
        cv.setRepresentative(clientele.getPerson());
        cv.setPriceUnit(offer.getPriceUnit());
        cv.setUnit((offer.getUnit() != null ? offer.getUnit() : goods.getUnit()));
        cv.setCounts(String.valueOf(order.getNumber()));
        cv.setStatus(order.getCheckStatus());
        Date date = order.getDeliveryDay();
        Date dateEnd = order.getDeliveryDayEnd();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        cv.setDeliveryDate(order.getDeliveryType().equals("0") ? sdf1.format(date) : sdf1.format(date) + " 至 " + sdf1.format(dateEnd));
//        cv.setDeliveryWay(order.getDeliveryType().equals("0") ? "自提" : "免费配送");
        if (order.getPickUpMethod().equals("1")) {
            if (order.getAddress() != null) {
                Address address = addressDao.selectByPrimaryKey(Integer.valueOf(order.getAddress()));
                cv.setDeliveryWay("卖方送货," + (address.getRegion() == null ? "" : address.getRegion()) + address.getDetail());
            } else {
                cv.setDeliveryWay(clientele.getAddress());
            }
        } else {
            cv.setDeliveryWay("需方自提" + offer.getDeliverPlace());
        }
        cv.setDescription(goods.getDesc());
        cv.setPaymentWay(order.getPayMethod().equals("0") ? "银行电汇" : (order.getPayMethod().equals("1") ? "承兑汇票" : (order.getPayMethod().equals("2") ? "国内信用证" : "")));
        cv.setPaymentDate(new SimpleDateFormat("yyyy-MM-dd").format(order.getPayDate()));
        Integer freeDay = (Integer.valueOf(order.getFreeStoreDay()));
        if (freeDay > 0) {
            freeDay -= 1;
        }
        BigDecimal bg = BigDecimal.valueOf(System.currentTimeMillis()).add(BigDecimal.valueOf(1000 * 60 * 60 * 24 * (long) freeDay));
        cv.setFreeDate((order.getFreeStoreType().equals("0") ? new SimpleDateFormat("yyyy-MM-dd").format(new Date(bg.longValue())) : ("交割日起" + order.getFreeStoreDay() + "天")));
        cv.setStorePrice("");
        cv.setWrap(offer.getPackSpec());
        cv.setTimePlace(new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " 上海");
        cv.setPrice(String.valueOf(order.getActualPrice()));
        BigDecimal d = order.getActualPrice().multiply(order.getNumber());
        cv.setMoney(String.valueOf(d));
        cv.setContractValue(PrintContract.change(d.doubleValue()));
        BaseResult<Object> res = new BaseResult(true, cv);

        sysLogService.log("合同打印", request, arg.getId(), Action.orderType);

        return res;
    }

    /**
     * 获取订单合同
     *
     * @param order
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getOrderPaper", method = RequestMethod.GET)
    public BaseResult<Object> getOrderPaper(Order order, HttpServletRequest request) {
        if (order.getId() == null) {
            return new BaseResult(false, "参数非法");
        }
        OrderPaper op1 = new OrderPaper();
        op1.setOrderId(String.valueOf(order.getId()));
//        op1.setType("0");
        op1.setOrderType("0");
        OrderPaper op = orderPaperMapper.selectByOrderIdAndOrderType(op1);
        Order order_ = depService.selectByPrimaryKey(order.getId());
        Map<Object, Object> o = new HashMap<Object, Object>();
        if (op != null) {
            if (op.getPaper() != null) {
                o.put("body", new String(op.getPaper()));
            } else {
                o.put("body", "");
            }
            o.put("type", op.getType());
            o.put("path", op.getPath());
            o.put("single", op.getSingle());
            o.put("checkStatus", order_.getCheckStatus());
            o.put("signatureStatus", op.getSignatureStatus());
            o.put("couple", op.getCouple());
        }
        sysLogService.log("打印合同操作", request, order.getId(), Action.orderType);
        return new BaseResult(true, o);
    }

    @RequestMapping(value = "/{id}-{clientleName}.pdf")
    public OutputStream toPdf(Order order, String id, String clientName, HttpSession session, HttpServletResponse response, HttpServletRequest request) throws DocumentException, TemplateException, IOException {
        OrderPaper op = orderPaperService.selectByOrderId(String.valueOf(order.getId()));
        String path = PdfHelper.getPath();
        ClassPathResource resource = new ClassPathResource("paper/order.ftl");
        Map<Object, Object> o = new HashMap<Object, Object>();
        o.put("body", new String(op.getPaper()));
//        System.out.println(o.get("body").toString());
        String path_ = resource.getURL().toString().replace("paper/order.ftl", "");
        sysLogService.log("合同PDF下载", request, order.getId(), Action.orderType);
        return PdfUtils.generateToServletOutputStream(path_.replace("file:" + (path_.indexOf("usr/") > -1 ? "" : "/"), ""), "paper/order.ftl",
                resource.getURL().toString().replace("paper/order.ftl", ""), o, response);
    }

    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/save-paper", method = RequestMethod.POST)
    public BaseResult savePaper(OrderPaper op, HttpSession session, HttpServletRequest request) {
        User user = (User) session.getAttribute(Constants.USER);
        op.setOrderType("0");
        OrderPaper op_res = orderPaperMapper.selectByOrderIdAndOrderType(op);
        int res = 0;
        if (op_res == null) {
            op.setUserId(String.valueOf(user.getId()));
            op.setOrderType("0"); // 销售合同
            res = orderPaperService.insertSelective(op);
        } else {
            op_res.setUserId(String.valueOf(user.getId()));
            op_res.setPaper(op.getPaper());
            op_res.setPath(op.getPath());
            op_res.setType(op.getType());
            op_res.setSingle(op.getSingle());
            op_res.setCouple(op.getCouple());
            if ("1".equals(op.getSignatureStatus())) {
                op_res.setSignatureStatus("1"); // 签章完成
            }
            res = orderPaperService.updateByPrimaryKeySelective(op_res);
            return new BaseResult(true, res);
        }
        if (res > 0) {
            String type = "";
            if (op.getPaper() != null) {
                type = OrderConstants.ORDER_SAVE_PAPER;
            } else if (op.getPath() != null) {
                type = OrderConstants.ORDER_UPLOAD_PAPER;
            } else if (op.getSingle() != null) {
                type = OrderConstants.ORDER_UPLOAD_SINGLE_PAPER;
            } else if (op.getCouple() != null) {
                type = OrderConstants.ORDER_UPLOAD_COUPLE_PAPER;
            }
            orderOperateLogService.insertLog(String.valueOf(user.getId()), type, op.getOrderId());
        }
        sysLogService.log("合同保存", request, Integer.valueOf(op.getOrderId()), Action.orderType);

        return new BaseResult(true, res);
    }


    /**
     * @param arg
     * @return
     */
    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public BaseResult<Integer> update(Order arg, HttpServletRequest request) {
        arg.setCheckStatus(null);//禁止通过update审核
        arg.setActualPrice(null); //禁止通过update收款
        arg.setPayStatus(null); //禁止通过update收款
        int service_res = depService.updateByPrimaryKeySelective(arg);
        if (arg.getBusinessId() != null && arg.getSalesName() != null) {

        }
        sysLogService.log("销售订单更新", request, arg.getId(), Action.orderType);
        BaseResult<Integer> res = new BaseResult<Integer>(true, service_res);
        return res;
    }

    /**
     * 收款
     *
     * @param arg
     * @return
     */
    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/payed", method = RequestMethod.POST)
    public BaseResult<Object> payed(Order arg, HttpSession session, HttpServletRequest request) {
        Order order = new Order();
        BaseResult<Object> res = null;
        User user = (User) session.getAttribute(Constants.USER);
        order.setPayStatus("1");
        Order service_res = depService.selectByPrimaryKey(arg.getId());
        if (service_res != null) {
            if (!"0".equals(service_res.getStatus())) {
                return new BaseResult(false, "订单状态不在执行中，不能再次收款!", 403);
            }
            if (service_res.getPayStatus().equals("1")) {
                return new BaseResult(false, "订单已经收款，不能再次收款!", 403);
            }
            order.setActualTotal(service_res.getActualTotal());
            order.setId(arg.getId());
            order.setOfferId(String.valueOf(user.getId())); //操作员
            Integer pay_res = (Integer) depService.payed(order);
            if (pay_res > 0) {
                sysLogService.log("订单付款", request, order.getId(), Action.orderType);
                orderOperateLogService.insertLog(String.valueOf(user.getId()), OrderConstants.ORDER_RECEIVE_MONEY, arg.getId().toString());
            }
            res = new BaseResult(true, pay_res);
        } else {
            res = new BaseResult(false, "订单不存在!", 403);
        }
        return res;
    }


    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/updatePrice", method = RequestMethod.POST)
    public BaseResult<Object> updatePrice(Order arg, HttpSession session, HttpServletRequest request) {
        User user = (User) session.getAttribute(Constants.USER);
        if (user == null) {
            return new BaseResult(false, "未登录!", 401);
        }
        Order order = depService.selectByPrimaryKey(arg.getId());
        Object service_res = depService.updatePrice(arg);
        if (service_res instanceof String) {
            return new BaseResult(false, service_res.toString(), 403);
        } else if (service_res instanceof Integer) {
            int service_ = (int) service_res;
            if (service_ > 0) { //
                sysLogService.log("更新价格:" + order.getActualPrice() + "->" + arg.getActualPrice(), request, order.getId(), Action.orderType);
                orderOperateLogService.insertLog(String.valueOf(user.getId()), OrderConstants.ORDER_UPDATE_PRICE, arg.getId().toString(), order.getActualPrice() + "->" + arg.getActualPrice());
            }
        }
        BaseResult<Object> res = new BaseResult(true, service_res);
        return res;
    }

    /**
     * 强制终止订单执行
     *
     * @param arg
     * @return
     */
    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/forceEnd", method = RequestMethod.POST)
    public BaseResult<Object> forceEnd(Order arg, HttpSession session, HttpServletRequest request) {
        User user = (User) session.getAttribute(Constants.USER);
        if (user == null) {
            return new BaseResult(false, "未登录!", 401);
        }
        Order order = new Order();
        order.setId(arg.getId());
        order.setStatus("2");
        Object service_res = depService.forceEnd(order);
        if (service_res instanceof String) {
            return new BaseResult(false, service_res.toString(), 403);
        } else if (service_res instanceof Integer) {
            int service_ = (int) service_res;
            if (service_ > 0) { //
                sysLogService.log("强制执行完毕", request, order.getId(), Action.orderType);
                orderOperateLogService.insertLog(String.valueOf(user.getId()), OrderConstants.ORDER_FORCE_END, arg.getId().toString());
            }
        }
        BaseResult<Object> res = new BaseResult(true, service_res);
        return res;
    }

    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/endOrder", method = RequestMethod.POST)
    public BaseResult<Object> endOrder(Order arg, HttpSession session, HttpServletRequest request) {
        User user = (User) session.getAttribute(Constants.USER);
        if (user == null) {
            return new BaseResult(false, "未登录!", 401);
        }
        Order order = new Order();
        order.setId(arg.getId());
        order.setStatus("1");
        order.setReason(arg.getReason());
        List<String> list1 = goodsService.judgeOperator(Integer.valueOf(user.getId()));
        Order order1 = depService.selectByPrimaryKey(arg.getId());
        if (list1.indexOf(order1.getGoodsId()) == -1) { //非产品运营人员
            if (String.valueOf(user.getId()).equals(order1.getBusinessId())) {
                return new BaseResult(false, "业务员，不能终止执行", 403);
            }
        }
        Object service_res = depService.forceEnd(order);
        if (service_res instanceof String) {
            return new BaseResult(false, service_res.toString(), 403);
        } else if (service_res instanceof Integer) {
            int service_ = (int) service_res;
            if (service_ > 0) { //
                sysLogService.log("终止执行", request, order.getId(), Action.orderType);
                orderOperateLogService.insertLog(String.valueOf(user.getId()), OrderConstants.ORDER_END, arg.getId().toString());
            }
        }
        BaseResult<Object> res = new BaseResult(true, service_res);
        return res;
    }

    @SameUrlData
    @ResponseBody
    @RequestMapping(value = "/checkStatus", method = RequestMethod.POST)
    public BaseResult<Object> checkStatus(Order arg, HttpSession session, HttpServletRequest request) {
        User user = (User) session.getAttribute(Constants.USER);

        arg.setChecker(String.valueOf(user.getId()));
        arg.setCheckTime(new Date());
        // 审核
        Object service_res = depService.checkOrder(arg); // 审核
        if (service_res instanceof String) {
            return new BaseResult<Object>(false, service_res.toString(), 403);
        } else if (service_res instanceof Integer) {
            int service_ = (int) service_res;
            if (service_ > 0) { //
                sysLogService.log("1".equals(arg.getCheckStatus()) ? "审核通过" : "审核拒绝", request, arg.getId(), Action.orderType);
                orderOperateLogService.insertLog(String.valueOf(user.getId()), OrderConstants.ORDER_CHECK, arg.getId().toString(), "1".equals(arg.getCheckStatus()) ? "审核通过" : "审核拒绝");
            }
        }
        BaseResult<Object> res = new BaseResult(true, service_res);
        return res;
    }

    /***
     * 分页查询
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/query", method = RequestMethod.GET)
    public ListResult query(OrderVo arg, HttpSession session, boolean isExport) {
        UserVo user = (UserVo) session.getAttribute(Constants.USER);
        Boolean isManger = false;
        for (Role role : user.getRoles()) {
            if (String.valueOf(role.getId()).equals(Constants.SUPER_MANAGER_ROLE_ID)) { /// 超级管理员账户判断
                isManger = true;
            }
        }
        if (!isManger) { //运营账户判断判断
            List<String> list = goodsService.judgeOperator(user.getId());
            if (list.size() == 0) {
                return new ListResult(false, "非运营或超级管理员角色账号，无权访问!", 403);
            }
            arg.setList(list);
        }
        arg.setSalesName(String.valueOf(user.getId())); //
        if (isExport) return getExport(arg);
        List<OrderVo> list_order = depService.queryByPage(arg);
        int total = depService.queryCount(arg);
        Pagination page = new Pagination(arg.getPage(), total, arg.getSize());
        ListResult res = new ListResult(true, list_order);
        res.setPage(page);
        return res;
    }

    public ListResult getExport(OrderVo arg) {
        arg.setPage(0);
        arg.setSize(Integer.MAX_VALUE);
        List<OrderVo> list_order = depService.queryByPage(arg);
        return new ListResult(true, list_order);
    }

    @ResponseBody
    @RequestMapping(value = "/queryNeedPay", method = RequestMethod.GET)
    public ListResult queryNeedPay(OrderVo arg, HttpSession session, boolean isExport) {
        if (isExport) {
            arg.setPage(0);
            arg.setSize(Integer.MAX_VALUE);
            List<OrderVo> list_order = depService.queryByPage(arg);
            return new ListResult(true, list_order);
        }
        List<OrderVo> list_order = depService.queryNeedPayOrdersByPage(arg);
        int total = depService.queryNeedPayOrdersCount(arg);
        Pagination page = new Pagination(arg.getPage(), total, arg.getSize());
        ListResult res = new ListResult(true, list_order);
        res.setPage(page);
        return res;
    }

    /***
     *  销售应收明细
     * @param arg
     * @param session
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @SameUrlData
    @RequestMapping(value = "/exportNeedPay/{verified}", method = RequestMethod.GET)
    public OutputStream queryNeedPayExport(OrderVo arg, HttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException {

        ListResult lr = queryNeedPay(arg, session, true);
        List<OrderVo> list = (List<OrderVo>) lr.getList();
        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("application/binary;charset=" + "UTF-8");
        String fileName = Utils.processFileName(request, "销售应收明细Excel");
        response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xlsx");// 组装附件名称和格式
        response.setCharacterEncoding("UTF-8");
        String hql = "销售应收明细"; // sheet 名称
        List<Map> lm = new ArrayList<Map>();
        for (int i = 0; i < list.size(); i++) {
            Map map = new LinkedHashMap();
            OrderVo ov = list.get(i);
            map.put("客户名称", ov.getClienteleName());
            map.put("销售订单号", ov.getNo());
            map.put("产品", ov.getGoodsName());

            map.put("单价", ov.getActualPrice());
            map.put("数量", ov.getNumber());
            map.put("实提数量", ov.getActualNumber());
            map.put("订单状态", "1".equals(ov.getStatus()) ? "终止执行" : ("0".equals(ov.getStatus()) ? "执行中" : ("2".equals(ov.getStatus()) ? "强制执行完毕" : ("3".equals(ov.getStatus()) ? "执行完毕" : ""))));
            map.put("订单金额", ov.getActualTotal());

            if ("3".equals(ov.getApplyBack()) || ("2".equals(ov.getStatus()) || "3".equals(ov.getStatus())) && "1".equals(ov.getPayStatus())) {
                map.put("未收金额", 0);
            } else {
                map.put("未收金额", ov.getActualTotal().subtract(ov.getActualReceived()));
            }
            if ("3".equals(ov.getApplyBack())) {
                map.put("实收金额", ov.getActualPrice().multiply(ov.getActualNumber()));
            } else {
                map.put("实收金额", ov.getActualReceived());
            }
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
            map.put("付款日期", ov.getCreateAt() != null ? sdf1.format(ov.getCreateAt()) : null);
            lm.add(map);
        }
        return exportService.exportExcel(hql, lm, outputStream);
    }

    /***
     *  销售已收明细
     * @param arg
     * @param session
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @SameUrlData
    @RequestMapping(value = "/queryReceivedExport", method = RequestMethod.GET)
    public OutputStream queryReceivedExport(OrderVo arg, HttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException {

        ListResult lr = queryNeedPay(arg, session, true);
        List<OrderVo> list = (List<OrderVo>) lr.getList();
        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("application/binary;charset=" + "UTF-8");
        String fileName = Utils.processFileName(request, "销售已收明细Excel");
        response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xlsx");// 组装附件名称和格式
        response.setCharacterEncoding("UTF-8");
        String hql = "销售已收明细"; // sheet 名称
        List<Map> lm = new ArrayList<Map>();
        for (int i = 0; i < list.size(); i++) {
            Map map = new LinkedHashMap();
            OrderVo ov = list.get(i);
            map.put("销售订单号", ov.getNo());
            map.put("产品", ov.getGoodsName());
            map.put("订单金额", ov.getActualTotal());

            if ("3".equals(ov.getApplyBack()) || ("2".equals(ov.getStatus()) || "3".equals(ov.getStatus())) && "1".equals(ov.getPayStatus())) {
                map.put("未收金额", 0);
            } else {
                map.put("未收金额", ov.getActualTotal().subtract(ov.getActualReceived()));
            }
            if ("3".equals(ov.getApplyBack())) {
                map.put("实收金额", ov.getActualPrice().multiply(ov.getActualNumber()));
            } else {
                map.put("实收金额", ov.getActualReceived());
            }
            map.put("客户名称", ov.getClienteleName());
            lm.add(map);
        }
        return exportService.exportExcel(hql, lm, outputStream);
    }

    @ResponseBody
    @RequestMapping(value = "/queryByClienteleIdAndOfferId", method = RequestMethod.GET)
    public ListResult queryByClienteleIdAndOfferId(OrderVo arg) {
        List<OrderVo> list = depService.queryOrdersByOfferIdAndClienteleId(arg);
        int total = depService.queryOrdersCountByOfferIdAndClienteleId(arg);
        Pagination page = new Pagination(arg.getPage(), total, arg.getSize());
        ListResult res = new ListResult(true, list);
        res.setPage(page);
        return res;
    }

    /**
     * 某一客户销售订单
     *
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryByClienteleId", method = RequestMethod.GET)
    public ListResult queryByClienteleId(OrderVo arg) {
        List<OrderVo> list = depService.queryOrdersClienteleId(arg);
        ListResult res = new ListResult(true, list);
        return res;
    }

    /*
     客户需需付款的销售订单
     */
    @ResponseBody
    @RequestMapping(value = "/queryClienteleNeedPayOrders", method = RequestMethod.GET)
    public ListResult queryClienteleNeedPayOrders(OrderVo arg) {
        List<OrderVo> list = depService.queryClienteleNeedPayOrders(arg);
        ListResult res = new ListResult(true, list);
        return res;
    }


    @ResponseBody
    @RequestMapping(value = "/queryMyOrder", method = RequestMethod.GET)
    public ListResult<Object> queryMyOrder(OrderVo arg, HttpSession session) {

        User user = (User) session.getAttribute(Constants.USER);
        ListResult<Object> res;
        if (user == null) {
            res = new ListResult(false, "请登录!", 401);
            return res;
        }
        List<OrderVo> list = depService.queryMyOrdersByPage(arg);
        int total = depService.queryMyOrderCount(arg);
        Pagination page = new Pagination(arg.getPage(), total, arg.getSize());
        res = new ListResult(true, list);
        res.setPage(page);
        return res;
    }

    /**
     * 导出 订单功能
     *
     * @param arg
     * @param session
     * @return
     */
    @SameUrlData
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public OutputStream export(OrderVo arg, HttpSession session, HttpServletResponse response, HttpServletRequest request) throws IOException {
        ListResult lr = query(arg, session, true);
        List<OrderVo> list = (List<OrderVo>) lr.getList();
        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("application/binary;charset=" + "UTF-8");
        String fileName = Utils.processFileName(request, "订单Excel");
        response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xlsx");// 组装附件名称和格式
        response.setCharacterEncoding("UTF-8");
        String hql = "订单"; // sheet 名称
        List<Map> lm = new ArrayList<Map>();
        for (int i = 0; i < list.size(); i++) {
            Map map = new LinkedHashMap();
            OrderVo ov = list.get(i);
            map.put("订单编号", ov.getNo());
            map.put("客户名称", ov.getClienteleName());
            map.put("付款/发货/审核状态",
                    (ov.getPayStatus().equals("0") ? "未付款" : (ov.getPayStatus().equals("1") ? "已付款" : "部分付款")) + "/" +
                            (ov.getDeliverStatus().equals("0") ? "未发货" : (ov.getDeliverStatus().equals("1") ? "已全部发货" : "部分发货")) + "/" +
                            (ov.getCheckStatus().equals("0") ? "未审核" : (ov.getCheckStatus().equals("1") ? "通过" : "未通过"))
            );
            map.put("审核说明", ov.getReason());
            map.put("货物名称", ov.getGoodsName());
            map.put("品质规格", ov.getQuality());
            map.put("单价", ov.getActualPrice());
            map.put("数量", ov.getNumber());
            map.put("实提数量", ov.getActualNumber());
            map.put("发货数量", ov.getDeliverNumber());
            map.put("供货地", ov.getDeliverPlace());
            map.put("总金额", ov.getActualTotal());
            map.put("实收金额", ov.getActualTotal());
            map.put("订单状态", "1".equals(ov.getStatus()) ? "终止执行" : ("0".equals(ov.getStatus()) ? "执行中" : ("2".equals(ov.getStatus()) ? "强制执行完毕" : ("3".equals(ov.getStatus()) ? "执行完毕" : ""))));
            map.put("操作员", ov.getSaleName());
            map.put("业务员", ov.getSalesName());
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            map.put("下单时间", ov.getCreateAt() != null ? sdf1.format(ov.getCreateAt()) : null);
            lm.add(map);
        }
        return exportService.exportExcel(hql, lm, outputStream);
    }
}
